$(function () {
    init_table();
    init_selectUser();
    /**初始化标签得内容**/
    $.post(ctx+"saleConfig/selectSaletag",{},function (r) {
        if (r.code == 0){
            var data = r.msg;
            $.each(data,function (index,val) {
                var div =  $(' <div class="text-left border-bottom-1"></div>');
                var fistdiv  ='<div class="border-bottom-1 p-t-3"><div class="checkbox m-0"><span class="m-r-15 m-l-5">'+val.parent.tagGroupName+'</span>\n' +
                    '<label><input type="checkbox" style="margin: 1px -20px 0px;" />不包含 <input type="hidden" value='+val.parent.tagSelect+' /></label></div></div>';
                div.append(fistdiv);
                var cc = $("<div class='m-t-5 p-3 text-left'><input type='hidden' value="+val.parent.tagSelect+" /></div>");
                $.each(val.children,function (i,v) {
                    cc.append('<button type="button" onclick="selectTagIscheck(this)" data-id="'+v.tagUuids+'" ' +
                        'class="btn btn-xs btn-link width-100 m-l-5 p-2 m-b-5 f-s-12 border-solid-g">'+v.tagName+'</button>');
                });
                div.append(cc);
                $("#selectTag").append(div);
            });
        }else{
            $JuXue.n_danger(r.msg);
        }
    });
    /**初始化客户的阶段**/
    $.post(ctx+"saleConfig/initTrackTable",function (r) {
        var data = r.data;
        var defaultbtn = '<button type="button" class="btn btn-link m-l-10 p-3 btn-primary" onclick="selectTrack(this);" data="">不限</button>';
        $("#customeTrack").empty().append(defaultbtn);
        $.each(data,function (index,val) {
            var btn = '<button type="button" class="btn btn-link m-l-10 p-3" onclick="selectTrack(this);" data="'+val.saleUuid+'">'+val.saleName+'</button>';
            $("#customeTrack").append(btn)
        });
    });

    /**初始化时间选择**/
    $("#select_time span").html(moment().subtract("days",29).format("YYYY-MM-DD")+" - "+moment().format("YYYY-MM-DD"));
    $('#select_time').daterangepicker({
        timePicker: true, //显示时间
        timePicker24Hour: true, //时间制
        timePickerSeconds: true, //时间显示到秒
        startDate: moment().hours(0).minutes(0).seconds(0), //设置开始日期
        endDate: moment(new Date()), //设置结束器日期
        maxDate: moment(new Date()), //设置最大日期
        "opens": "center",
        ranges: {
            '今天': [moment(), moment()],'昨天': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
            '上周': [moment().subtract(6, 'days'), moment()],
            '前30天': [moment().subtract(29, 'days'), moment()],
            '本月': [moment().startOf('month'), moment().endOf('month')],
            '上月': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
        },
        showWeekNumbers: true,
        locale: {
            format: "YYYY-MM-DD HH:mm:ss", //设置显示格式
            applyLabel: '确定', //确定按钮文本
            cancelLabel: '取消', //取消按钮文本
            customRangeLabel: '自定义',
            daysOfWeek: ['日', '一', '二', '三', '四', '五', '六'],
            monthNames: ['一月', '二月', '三月', '四月', '五月', '六月',
                '七月', '八月', '九月', '十月', '十一月', '十二月'
            ],
            firstDay: 1
        },
    }).on('apply.daterangepicker', function(ev, picker) {
        var starttime = picker.startDate.format('YYYY-MM-DD');
        var endtime = picker.endDate.format('YYYY-MM-DD');
        $("#select_time span").html(starttime+" - "+endtime);
        $("#starttime").val(starttime);
        $("#endtime").val(endtime);
        $JuXue.refreshTable('sale_cusManage');
    });
});

/**初始化数据**/
function init_table(){
    var settings = {
        url: ctx + "SaleManage/getMyCustomerManageList",
        pageSize: 15,
        sortable: true,                     //是否启用排序
        sortOrder: "desc",                 //排序方式
        sortName: 'recordtime',//排序字段
        onLoadSuccess: function () {
            $("[data-toggle='tooltip']").tooltip();//初始化 沟通方式的鼠标
            var ass = $("#expandManage").hasClass("height-full width-full m-0");
            if(ass){
                $("#sale_cusManage").find("tbody").eq(0).css("display","block").css("max-height","570px").css("overflow-y","scroll");
            }else{
                $("#sale_cusManage").find("tbody").eq(0).css("display","block").css("max-height","370px").css("overflow-y","scroll");
            }
            $("#sale_cusManage").find("thead").eq(0).css("display","block");
            var _width=$('#sale_cusManage').width();
            $('#sale_cusManage th:first-child').width(_width*0.1);
            $('#sale_cusManage td:first-child').width(_width*0.1);

            $('#sale_cusManage th:nth-child(2)').width(_width*0.1);
            $('#sale_cusManage td:nth-child(2)').width(_width*0.1);

            $('#sale_cusManage th:nth-child(3)').width(_width*0.1);
            $('#sale_cusManage td:nth-child(3)').width(_width*0.1);

            $('#sale_cusManage th:nth-child(4)').width(_width*0.1);
            $('#sale_cusManage td:nth-child(4)').width(_width*0.1);

            $('#sale_cusManage th:nth-child(5)').width(_width*0.2);
            $('#sale_cusManage td:nth-child(5)').width(_width*0.2);

            $('#sale_cusManage th:nth-child(6)').width(_width*0.1);
            $('#sale_cusManage td:nth-child(6)').width(_width*0.1);

            $('#sale_cusManage th:nth-child(7)').width(_width*0.2);
            $('#sale_cusManage td:nth-child(7)').width(_width*0.2);

            $('#sale_cusManage th:nth-child(8)').width(_width*0.1);
            $('#sale_cusManage td:nth-child(8)').width(_width*0.1);
        },
        queryParams: function(params) {
            return {
                pageSize: params.limit,
                pageNum: params.offset / params.limit + 1,
                sort: params.sort,      //排序列名
                sortOrder: params.order, //排位命令（desc，asc）
                userid   :  $("#genjiren").val(),   //跟进人
                stage:      $("#slectcusStage").val(),//客户阶段
                otherLabel: $("#selecttagOnter").val(),//其他标签
                label:      $("#selectContion").val(),//包含标签
                notLabel:   $("#selectNotContion").val(),//不包含标签
                timeType:   $("#timeSelect").val(), //时间类型
                beforeTime: $("#starttime").val(), //开始时间
                afterTime:  $("#endtime").val(),//结束时间
                toolType :  $("#typeTool").val(),//类型
                toolTong :  $("#tongTool").val(), //通讯
                types    :  $("#SourType").val(),//资源类型
                plan     :  $("#selectPlanId").val(), //销售计划
                searchType: $("#searchType").val(),  //综合查询类型
                searchValue :$("#searchValue").val() //综合查询的值
            };
        },
        columns: [{
            checkbox: true,
            width: '5%',
        }, {
            field: 'nickname',
            title: '客户名称',
            width: '10%',
            clickToSelect:false,
            formatter:function (value, row, index) {
                return "<a href='javascript:void(0)' onclick='viewMycusDetail(this);' uuid = '"+row.uuid+"' data-type='"+row.types+"' data-id='"+row.id+"'>"+value+"</a>";
            }
        }, {
            field: 'types',
            title: '类型',
            width: '10%',
            formatter:function (value, row, index) {
                var typename = "";
                if(value=="1"){
                    typename = "推广";
                }else if(value=="2"){
                    typename = "网校";
                }else if(value=="3"){
                    typename = "大资源";
                }else{
                    typename = "个人";
                }
                return typename;
            }

        }, {
            field: 'mobile',
            title: '沟通方式',
            clickToSelect:false,
            width: '10%',
            formatter:function (value,row,index) {
                var qq = row.qq;
                var wechat = row.wechat;
                var monile = "";
                var utype = row.types;
                var uid = row.id;
                var cn = row.nickname;
                if (value != null && value != ""){
                    monile = '<a href="#" data-toggle="tooltip" data-placement="top" title="'+value+'" utype="'+utype+'" uid="'+uid+'" cn = "'+cn+'" onclick="makePhoneCall(this)" phone="'+value+'" ><i class="fa fa-phone  text-success m-3"></i></a>';
                }
                var qqlabel  = "";
                if (qq!=null && qq != ""){
                    qqlabel = '<a href="#" data-toggle="tooltip" data-placement="top" title="'+qq+'"><i class="fa fa-qq  text-success m-3"></i></a>';
                }
                var wechatlabel = "";
                if (wechat!=null && wechat != ""){
                    wechatlabel = '<a href="#" data-toggle="tooltip" data-placement="top" title="'+wechat+'"><i class="fa fa-weixin  text-success m-3"></i></a>';
                }
                return monile+qqlabel+wechatlabel;
            }
        }, {
            field: 'label',
            title: '客户标签',
            width: '20%',
            formatter:function (value, row, index) {
                if (value !=null){
                    var label = value.split(",");
                    var str = "";
                    $.each(label,function (i,v) {
                        str += '<span type="button" class="btn btn-xs btn-link m-l-3 m-b-3  f-s-10 border-solid-g">'+v+'</span>';
                    });
                    return str;
                }
                return '-';
            }
        }, {
            field: 'receiver',
            title: '跟进人',
            width: '10%',
        }, {
            field: 'recordtime',
            title: '最近动态',
            sortable: true,
            width: '20%',
            formatter:function (value, row, index) {
                var time = row.recordtime;
                var record = row.record;
                return time+"<br/>"+record;
            }
        },{
            field: 'createtime',
            title: '创建时间',
            sortable:true,
            width: '15%',
            formatter:function (value, row, index) {
                return value.substring(0,10);
            }
        }]
    };
    $JuXue.initTable('sale_cusManage', settings);
}

/**初始化选择人员**/
function init_selectUser(){
    $.post(ctx+"dept/getUserAndDeptByTreeWhisRole",{},function (r) {
        var array  = r.msg;
        $("#sale_user_manage").jstree({
            "core": {
                "multiple": true,//单选
                "data":array,
                "icon":false,
                "themes":{
                    "icons":false
                }
            },
            "checkbox" : {
                "keep_selected_style" : false
            },
            "plugins" : [ "wholerow", "checkbox" ]
        });
        // 获得点击节点的id
        $('#sale_user_manage').on("changed.jstree", function (e, data) {
            var nodeid = data.node.id;
            var text = data.node.text;
            var action = data.action;;
            if (action == "deselect_node") {
                $("#otherUserSelect").find("div").each(function () {
                    var data_id = $(this).attr("data-id");
                    if (data_id == nodeid) $(this).remove();
                });
            }else{
                /**判断是不是超过 5个 超过5个则不能继续追加**/
                var divlength = $("#otherUserSelect").find("div");
                if(divlength.length >= 5){
                    $JuXue.n_danger("选择查询类型不能超过5个");
                    $("#sale_user_manage").jstree("deselect_node",nodeid);
                    return;
                }else{
                    if(divlength.length >0){
                        var ble = false;
                        $("#otherUserSelect").find("div").each(function () {
                            var data_id = $(this).attr("data-id");
                            if (data_id == nodeid){ble = true;}
                        });
                        if(!ble){
                            var label = "<div class='label label-danger p-3 m-3 ' data-id='"+nodeid+"'>"+text+"</div>";
                            $("#otherUserSelect").append(label);
                        }
                    }else{
                        var label = "<div class='label label-danger p-3 m-3 ' data-id='"+nodeid+"'>"+text+"</div>";
                        $("#otherUserSelect").append(label);
                    }
                }
            }
        });
    });
}
/**选择员工**/
function selectUserList(){
    $('#saleUsersManage').removeClass('open');
    var allUser = $('#sale_user_manage').jstree(true).get_selected(false);//获得整个树
    var users = allUser.join(",");
    $("#genjiren").val(users);
    $JuXue.refreshTable('sale_cusManage');
}
/**选择标签**/
function selectTagIscheck(btn) {
    var $parentcheck  = $(btn).parent();
    var isMultiInput = $parentcheck.children("input:first-child").val();
    if (isMultiInput == "1"){
        //多选
        var ishave = $(btn).hasClass("btn-primary");
        if (ishave) {
            $(btn).removeClass("btn-primary");
        }else{
            $(btn).addClass("btn-primary");
        }
    }else{
        //单选
        var ishave = $(btn).hasClass("btn-primary");
        if (ishave) {
            $parentcheck.find("button").each(function () {
                $(this).removeClass("btn-primary");
            });
        }else{
            $parentcheck.find("button").each(function () {
                $(this).removeClass("btn-primary");
            });
            $(btn).addClass("btn-primary");
        }
    }
}

/**确定标签**/
function labelSelectSure() {
    var div = $("#selectTag").children("div");
    //包含
    var selectids = new Array();
    var selectnames = new Array();
    //不包含
    var notselectids = new Array();
    var notselectnames = new Array();
    $.each(div,function (index,val) {
        var isChecked = $(this).find("input[type='checkbox']").eq(0).is(':checked');
        if (isChecked) {
            //如果选中 则表示不包含
            var btn = $(this).find("button");
            $.each(btn,function () {
                var isSelect = $(this).hasClass("btn-primary");
                if (isSelect){
                    var notselectid = $(this).attr("data-id");
                    var notselectname = $(this).text();
                    notselectids.push(notselectid);notselectnames.push(notselectname);
                }
            });
        }else{
            //包含
            var btn = $(this).find("button");
            $.each(btn,function () {
                var isSelect = $(this).hasClass("btn-primary");
                if (isSelect){
                    var selectid = $(this).attr("data-id");
                    var selectname = $(this).text();
                    selectids.push(selectid);selectnames.push(selectname);
                }
            });
        }
    });
    var length = selectids.length+notselectids.length;
    if(length > 5){$JuXue.n_danger("标签选择不能大于5个");return ;}
    else {if (length <= 0){$("#otherselect").show();}else{$("#otherselect").hide();}}
    $("#drownSelect").empty();
    $.each(selectnames,function (i,v) {
        $("#drownSelect").append('<a type="button" class="btn btn-link m-l-10 p-3 f-s-10 btn-primary ">'+v+'</a>');
    });
    $.each(notselectnames,function (i,v) {
        $("#drownSelect").append('<a type="button" class="btn btn-link m-l-10 p-3 f-s-10 btn-default">'+v+'</a>');
    });
    $("#labelselect").removeClass("open");
    $("#selectContion").val(selectids.join(","));
    $("#selectNotContion").val(notselectids.join(","));
    $JuXue.refreshTable('sale_cusManage');

}
/**点击其他动态选项卡**/
function selectTagByOther(btn) {
    $("#otherselect").find("a").each(function () {
        $(this).removeClass("btn-primary");
    });
    $(btn).addClass("btn-primary");
    //动态加载
    var project = $(btn).attr("data-click");
    $("#selecttagOnter").val(project);
    $JuXue.refreshTable('sale_cusManage');
}
/**点击切换客户阶段**/
function selectTrack(btn) {
    $("#customeTrack").find("button").each(function () {
        $(this).removeClass("btn-primary");
    });
    $(btn).addClass("btn-primary");
    //动态加载
    var project = $(btn).attr("data");
    $("#slectcusStage").val(project);
    $JuXue.refreshTable('sale_cusManage');
}
/**综合查询搜索栏**/
function selectSearch(btn){
    $("#stype").text($(btn).text());
    var data_s = $(btn).attr("data");
    $("#searchType").val(data_s);
    $JuXue.refreshTable('sale_cusManage');
}

/**选择时间类型**/
function selectMyTime(btn) {
    var data_cliak = $(btn).attr("data-click");
    if(data_cliak === "selft"){
        $("#select_time").removeClass("hidden");
        $("#starttime").val(moment().subtract("days",29).format("YYYY-MM-DD"));
        $("#endtime").val(moment().format("YYYY-MM-DD"));
    }else{
        $("#select_time").addClass("hidden");
        $("#starttime").val('')
        $("#endtime").val('');
    }
    $("#timeRemove").find("button").each(function () {
        $(this).removeClass("btn-primary");
    });
    $(btn).addClass("btn-primary");
    $JuXue.refreshTable('sale_cusManage');
}
/**切换时间类型**/
function dynTime(btn) {
    var timeType = $(btn).attr("time");
    if (timeType!=undefined) $("#timeSelect").val(timeType);
    // $JuXue.refreshTable('myEmpTable');
}
/**选择通讯工具**/
function selectTool(btn) {
    $("#selectButton").find("button").each(function () {
        $(this).removeClass("btn-primary");
    });
    var dataId = $(btn).attr("data-id");
    var dataClick = $(btn).attr("data-click");
    if (dataId == ""){
        $("#selectTool").text("通讯工具筛选");
    }else if (dataId =="1") {
        if (dataClick == "1"){
            $("#selectTool").text("通讯工具: 有QQ");
        }else {
            $("#selectTool").text("通讯工具: 无QQ");
        }
    }else if(dataId =="2"){
        if (dataClick == "1"){
            $("#selectTool").text("通讯工具: 有邮箱");
        }else {
            $("#selectTool").text("通讯工具: 无邮箱");
        }
    }
    $("#tongTool").val(dataClick);
    $("#typeTool").val(dataId);
    $(btn).addClass("btn-primary");
    $JuXue.refreshTable('sale_cusManage');
}

/**选择有无销售计划**/
function selectSalePlan(btn) {
    $("#selectPlanButton").find("button").each(function () {
        $(this).removeClass("btn-primary");
    });
    var dataId = $(btn).attr("data-id");
    if (dataId == ""){
        $("#selectPaln").text("销售计划筛选");
    }else if (dataId =="1") {
        $("#selectPaln").text("销售计划: 有");
    }else if(dataId =="2"){
        $("#selectPaln").text("销售计划: 无");
    }
    $("#selectPlanId").val(dataId);
    $(btn).addClass("btn-primary");
    $JuXue.refreshTable('sale_cusManage');
}

/**选择资源类型工具**/
function selectmySourType(btn) {
    $("#selecttypeButton").find("button").each(function () {
        $(this).removeClass("btn-primary");
    });
    var dataId = $(btn).attr("data-id");
    if (dataId == ""){
        $("#selecttype").text("资源类型筛选");
    }else if (dataId =="1") {
        $("#selecttype").text("资源类型: 推广资源");
    }else if(dataId =="2"){
        $("#selecttype").text("资源类型: 网校资源");
    }else if(dataId == "3"){
        $("#selecttype").text("资源类型: 大资源 ");
    }else {
        $("#selecttype").text("资源类型: 个人资源");
    }
    $("#SourType").val(dataId);
    $(btn).addClass("btn-primary");
    $JuXue.refreshTable('sale_cusManage');
}

/**综合查询搜索栏**/
function selectSearch(btn){
    $("#stype").text($(btn).text());
    var data_s = $(btn).attr("data");
    $("#searchType").val(data_s);
    $JuXue.refreshTable('sale_cusManage');
}

/**加载客户详情页面*/
function viewMycusDetail(btn) {
    var type = $(btn).attr("data-type");
    var ids = $(btn).attr("data-id");
    $("#customer_uuid").val(ids);
    $("#customer_ids").val(ids);
    $("#customer_type").val(type);
    $.post(ctx+"myCustomer/loadCustomerDetail",{type:type},function (r) {
        $("#myCustomer-modal").empty().append(r).modal('show').draggable();
    });
}


